<template>
  <div>
    <basic-container>
      <!--数据报告模块-->
      <div class="search-form">
        <el-form
          ref="form"
          :model="queryForm"
          :rules="rules"
          label-width="100px"
          style="display: flex; flex-wrap: wrap"
        >
          <el-row :gutter="20" style="width: 100%">
            

            <el-col :span="6" style="margin-left: -55px">
              <el-form-item label="短ID:" prop="shortId">
                <el-input placeholder="请输入短ID" size="mini" v-model="queryForm.shortId" clearable
                          @keyup.enter.native="submitForm">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="素材名称:" prop="name">
                <el-input placeholder="请输入素材名称" size="mini" v-model="queryForm.name" clearable
                          @keyup.enter.native="submitForm">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="更新时间:">
                <el-date-picker
                  size="mini"
                  v-model="updateDateRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="submitForm"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>

           
            <el-col span="4"
                    style="min-width: 160px;display:flex;justify-content:flex-end;float: right;margin-top: 5px;margin-right: -16px">
              <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
                <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                           style="margin-right: 10px"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="清空" placement="top">
                <el-button id="id-business-offer-emptyForm" :class="emptyIcon" class="search-circle"
                           @click="resetSearch"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="搜索" placement="top">
                <el-button id="id-business-offer-searchForm-four" type="primary" icon="el-icon-search" size="mini"
                           @click="submitForm" style="margin-right: 0">
                  搜索
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="导出" placement="top">
                <el-button id="id-business-offer-export-excel" type="primary" icon="el-icon-download" size="mini"
                           @click="exportExcel" style="margin-right: 0">
                  导出
                </el-button>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row v-show="searchConceal" :gutter="20" style="width: 100%;">
            
            <el-col :span="5" style="margin-left: -55px">
              <el-form-item label="设计师:">
                <el-select v-model="queryForm.designer" size="mini" clearable filterable placeholder="请选择"
                           @change="submitForm">
                  <el-option
                    v-for="(item,index) in designerList"
                    :key="index"
                    :label="item.realName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5" style="margin-left: -55px">
              <el-form-item label="媒体:">
                <el-select
                  size="mini"
                  v-model="queryForm.platform"
                  placeholder="请选择"
                  clearable
                  @change="submitForm"
                >
                  <el-option
                    v-for="item in platformList"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="投放地区:">
                <el-select v-model="queryForm.nationList" size="mini" multiple clearable filterable placeholder="请选择"
                           @blur="submitForm">
                  <el-option
                    v-for="(item,index) in nationList"
                    :key="index"
                    :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="本地文件名:" prop="localFilename" >
                <el-input placeholder="请输入" size="mini" v-model="queryForm.localFilename"
                          clearable @keyup.enter.native="submitForm">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="操作系统">
                <el-select v-model="queryForm.os" placeholder="请选择" size="mini" clearable @change="submitForm">
                  <el-option
                    label="Android"
                    value="1">
                  </el-option>
                  <el-option
                    label="IOS"
                    value="2">
                  </el-option>
                  <el-option
                    label="Website"
                    value="3">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-dialog
        title="预览"
        :visible="mediaPreviewDialog.dialogVisible"
        width="80%"
        :modal-append-to-body="false"
        top="0px;"
        :close-on-click-modal="false"
        :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
        :append-to-body="true"
        style="text-align: center"
      >
        <img
          v-if="mediaPreviewDialog.dialogType === 'image'"
          :style="previewStyle()"
          :src="mediaPreviewDialog.previewUrl"
        />
        <video
          ref="video"
          v-if="mediaPreviewDialog.dialogType === 'video'"
          :src="mediaPreviewDialog.previewUrl"
          :style="previewStyle()"
          controls="controls"
        ></video>
      </el-dialog>

      <el-dialog
        :visible="creativeInfoDialog.dialogVisible"
        width="80%"
        :modal-append-to-body="false"
        top="0px;"
        :close-on-click-modal="false"
        :append-to-body="true"
        style="text-align: center"
        :before-close="
        () => {
        creativeInfoDialog.dialogVisible = false;
        }
      "
      >
        <creative-info v-if="creativeInfoDialog.dialogVisible"
                       :creative-id="creativeInfoDialog.creativeId"></creative-info>
      </el-dialog>
      <creative-performance-detail width="80%" ref="creativePerformanceDetail"></creative-performance-detail>
    </basic-container>
    <basic-container>
      <div class="tab-header clearfix">
        <div class="tab-header-left">
          <el-radio-group v-model="activeName" size="mini">
            <el-radio-button label="0">图片</el-radio-button>
            <el-radio-button label="1">视频</el-radio-button>
          </el-radio-group>
          <span>显示模板</span>
          <el-select v-model="templateSelect" placeholder="请选择" style="width: 125px; margin-right: 5px" size="mini"
                     @change="templateChange">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                    <el-button size="mini" @click="deleteTemplate(item.id, item.name)" type="text"><i
                      class="el-icon-delete"/></el-button>
                  </span>
            </el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleModelOpen">保存为模板</el-button>
        </div>
        <div class="tab-header-right">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button icon="el-icon-refresh" size="mini" circle @click="refreshChange"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="显隐" placement="top">
            <el-button icon="el-icon-s-operation" size="mini" circle @click="tableColumnDrawer = true"></el-button>
          </el-tooltip>
        </div>
      </div>
      <!--图片表格-->
      <el-table
        v-loading="loading"
        :data="activeName==='0'?imageData:videoData"
        border
        show-summary
        :summary-method="summaryMethod"
        @sort-change="sortTableData"
        :header-cell-style="iHeaderCellStyle"
        style="width: 100%">
        <el-table-column
          v-for="item in renderTableColumn"
          :key="item.value"
          :prop="item.value"
          :label="item.label"
          :sortable="item.sortable"
          :width="item.width?item.width:''">
          <template v-slot="{row}" v-if="item.value==='creativeUrl'">
            <div @click="handleMediaPreview(row)">
              <img
                v-show="dialogType(row.creativeUrl) == 'image'"
                width="100%"
                :src="row.creativeUrl"
              />
              <video
                v-show="dialogType(row.creativeUrl) == 'video'"
                :src="row.creativeUrl"
                style="width: 100%"
              ></video>
            </div>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='shortId'">
            <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onCreativeTagsClick(row)">{{
                row.shortId
              }}</a></div>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='designer'">
            {{ designerChange(row) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='ads'">
            {{ countAds(row) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='ctr'">
            {{ row.ctr }}%
          </template>
          <template v-slot="{row}" v-else-if="item.value==='cvr'">
            {{ row.cvr }}%
          </template>
          <template v-slot="{row}" v-else-if="item.value==='os'">
            {{ codeOS(row.os) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='performanceName'">
            <el-tooltip effect="dark" :content="row.performanceName" placement="left">
              <span class="over-flow">{{ row.performanceName }}</span>
            </el-tooltip>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='localFilename'">
            <el-tooltip effect="dark" :content="row.localFilename" placement="left">
              <span class="over-flow">{{ row.localFilename }}</span>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }" v-else-if="item.value==='onlineStatus'">
            <el-tag type="danger" v-if="row.status !== 2 && row.onlineStatus === 1">违规</el-tag>
            <el-tag type="success" v-else-if="row.onlineStatus === 1">在线</el-tag>
            <el-tag type="info" v-else>未在线</el-tag>
          </template>
        </el-table-column>
        <!--显隐-->
        <el-table-column
          fixed="right"
          label="操作"
          width="50">
          <template v-slot="{row}">
            <el-tooltip content="查看" placement="top">
              <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--底部-->
      <div class="bottom-page clearfix">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </basic-container>
    <el-drawer
      title="列显隐"
      size="800px"
      :visible.sync="tableColumnDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
      ref="drawer"
      @close="handleCloseTableColSet"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <el-transfer
          filterable
          v-model="tableColumnValue"
          :data="tableColumnData"
          :titles="['隐藏', '显示']"
          :props="{key: 'value',label: 'label'}"
          @left-check-change="filterLeftTableColumnData">
        </el-transfer>
      </cs-drawer-container>
    </el-drawer>
    <el-dialog :visible.sync="saveDialog" append-to-body width="30%"
               :close-on-click-modal="false" :show-close="false">
      <div>
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelRules"
                 style="margin: 0 auto;width: 80%;text-align: center">
          <el-form-item prop="modelFormat">
            <el-radio-group v-model="modelForm.modelFormat">
              <el-radio label="0" @change="setTemplateName(true)">
                保存为新模板
              </el-radio>
              <el-radio label="1" @change="setTemplateName(false)" :disabled="templateList.length === 0">覆盖当前的模板
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="modelName" label="模板名：" style="position: relative">
            <el-input size="mini" placeholder="请输入模板名称" v-model="modelForm.modelName"/>
            <span v-if="modelForm.modelFormat === '1'"
                  style="color: #f56c6c; position: absolute; left: 0; top: 86px; width: 200px; text-align: left; font-size: 12px">您可以对现有模板重命名</span>
          </el-form-item>
          <el-form-item style="margin-top: 45px">
            <el-button type="primary" size="mini" @click="saveModel" :disabled="saveTemplateloading">确定</el-button>
            <el-button size="mini" @click="saveDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  add,
  getDesignerList,
  getDetail,
  getList,
  getSubmitter,
  remove,
  update,
  exportExcel, getTemplateList, saveTemplate, deleteTemplate, getEventCreativeGroup
} from "@/api/offer/creativeperformance";
import creativePerformanceDetail from '@/views/creativeReport/components/creativeperformancedetail'
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {getOutList} from '@/api/business/share'
import {getSysDictList} from "@/api/system/dict";
import {findObject} from "@/util/util";
import {createEventHandler} from "@/util/events";
import {mapGetters} from "vuex";
import Moment from "moment";
import creativeInfo from "./components/creativeInfo";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";

export default {
  name: 'CreativePerformance',
  components: {
    creativePerformanceDetail,
    creativeInfo,
    CsDrawerContainer,
  },
  data() {
    let checkShortId = (rule, value, callback) => {
      const shortReg = /^\d{3,6}$/;
      if (value !== '' && !shortReg.test(value)) {
        callback(new Error('请输入3-6位数字!'))
      } else {
        callback()
      }
    };
    return {
      selectList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      resultList: [],
      information: [],
      designerList: [],
      now: "",
      lastWeek: "",
      agencyTenantList: [],
      submitterList: [],
      countryList: [],
      platformList: [],
      nationList: [],
      tabName: 0,
      activeName: '0',
      queryForm: {
        shortId: '',
        name: '',
        localFilename: '',
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        designer: null,
        creativeId: null,
      },
      form: {},
      query: {},
      rules: {
        shortId: [{required: false, validator: checkShortId, trigger: 'change'}],
      },
      updateDateRange: [],
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
      creativeInfoDialog: {
        dialogVisible: false,
        name: '',
        creativeId: '',
      },
      isAdvSharedOffer: false,
      // marco
      // 显隐抽屉
      saveTemplateloading: false,
      tableColumnDrawer: false,
      tableColumnValue: [],
      defaultTableColumnValue: ["creativeUrl", "shortId", "performanceName", "localFilename", "offerName", "designer", "platform", "country", "allExpend", "impressions", "clicks", "ctr", "installCost", "cvr"],
      tableColumnData: [],
      defaultTableColumnData: [
        {
          value: "creativeUrl",
          label: "素材",
          width: 150
        },
        {
          value: "shortId",
          label: "短Id",
          width: 100
        },
        {
          value: "performanceName",
          label: "素材名称",
        },
        {
          value: "localFilename",
          label: "本地文件名",
          width: 150
        },
        // {
        //   label: "状态",
        //   value: "onlineStatus",
        // },
        {
          value: "offerName",
          label: "订单名",
          width: 100
        },
        {
          value: "designer",
          label: "设计师",
          width: 100
        },
        {
          value: "platform",
          label: "媒体",
          width: 100
        },
        {
          value: "country",
          label: "投放地区",
          width: 100
        },
        // {
        //   label: "在线天数",
        //   value: "onlineDays",
        // },
        {
          value: "os",
          label: "操作系统",
          width: 100
        },
        {
          value: "ads",
          label: "关联广告数",
          sortable: true,
          width: 120
        },
        {
          value: "allExpend",
          label: "花费",
          sortable: true,
          width: 100,
        },
        {
          value: "impressions",
          label: "曝光",
          sortable: true,
          width: 100
        },
        {
          value: "clicks",
          label: "点击",
          sortable: true,
          width: 100
        },
        {
          value: "ctr",
          label: "CTR",
          sortable: true,
          width: 100
        },
        {
          value: "install",
          label: "安装",
          sortable: true,
          width: 100
        },
        {
          value: "installCost",
          label: "安装成本",
          sortable: true,
          width: 100
        },
        {
          value: "cvr",
          label: "CVR",
          sortable: true,
          width: 100
        },
      ],
      // 模板相关
      templateList: [],
      templateSelect: '',
      templateSelectOld: '',
      templateDefaultName: '',
      saveDialog: false,
      modelForm: {
        modelFormat: '0',
        modelName: '',
      },
      modelRules: {
        modelFormat: [{required: true, message: '请选择模板保存形式', trigger: 'change'}],
        modelName: [{required: true, message: '请输入模板名称', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}]
      },
      // 媒体事件
      eventData: []
    };
  },
  computed: {
    ...mapGetters(["permission", "offer", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.creativeperformance_add, false),
        viewBtn: this.vaildData(
          this.permission.creativeperformance_view,
          false
        ),
        delBtn: this.vaildData(
          this.permission.creativeperformance_delete,
          false
        ),
        editBtn: this.vaildData(
          this.permission.creativeperformance_edit,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    // marco
    // 显影穿梭框选择的对象
    renderTableColumn() {
      return this.tableColumnData.filter(item => this.tableColumnValue.includes(item.value))
    },
    // 选择的媒体事件
    selectedEventData() {
      return this.eventData.filter(item => this.tableColumnValue.includes(item.value)).map(item => item.value).join(',')
    },
    buildSearch() {
      let query = {...this.queryForm};
      delete query.nationList;
      if (this.updateDateRange != null && this.updateDateRange.length == 2) {
        query.beginDate = this.updateDateRange[0];
        query.endDate = this.updateDateRange[1];
      } else {
        query.beginDate = "";
        query.endDate = "";
      }
      query.country = this.queryForm.nationList.join(',')
      return query;
    },
  },
  watch: {
    activeName(val, oldVal) {
      if (val === oldVal) return
      this.onLoad(this.page)
    },
    // 第一次载入模板时校对不可选的项目
    tableColumnValue: {
      handler: 'filterTableColumnData',
      immediate: true
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },

  async created() {
    await this.getEventCreativeGroup()
    await this.getTemplateList()
    this.tableColumnValue = this.defaultTableColumnValue
    // 第一次进入显示上次模板
    if (this.templateList.length > 0) {
      this.modelForm.modelFormat = '0'
      this.modelForm.modelName = this.templateList[0].name
      this.templateSelect = this.templateList[0].id
      this.templateSelectOld = this.templateList[0].id
      const basicData = this.templateList[0].basicData.split(',')
      this.tableColumnValue = [...basicData]
    }
    //window.addEventListener('keyup', this.submitForm) //监听键盘事件
    this.updateDateRange = [Moment().subtract(7, "days").format("yyyy-MM-DD"), Moment().subtract(1, "days").format("yyyy-MM-DD")];
    this.query.beginDate = this.updateDateRange[0];
    this.query.endDate = this.updateDateRange[1];
    await this.onLoad(this.page)
    let self = this;
    this.eventHandler = createEventHandler("offerCenter").addListener(
      async (event) => {
        if (
          event.message == "offerChanged" &&
          event.offerId &&
          event.offerId !== ""
        ) {
          this.offer = event.offerId;
          this.queryForm = {
            shortId: '',
            name: '',
            localFilename: '',
            platform: null,
            nationList: [],
            designer: null,
            creativeId: null,
            os: ''
          };
          this.refresh();
          await this.getEventCreativeGroup()
          await this.getTemplateList()
          if (this.templateList.length > 0) {
            this.modelForm.modelFormat = '0'
            this.modelForm.modelName = this.templateList[0].name
            this.templateSelect = this.templateList[0].id
            const basicData = this.templateList[0].basicData.split(',')
            this.tableColumnValue = [...basicData]
          } else {
            this.modelForm.modelName = ''
            this.templateSelect = ''
            this.tableColumnValue = this.defaultTableColumnValue
          }
          await this.onLoad(this.page, {});
        }
      }
    );

    this.refresh();
    if (this.$route.query.creativeId) {
      this.activeName = this.$route.query.type === "图片" ? "0" : "1";
      if (this.$route.query.beginDate != null && this.$route.query.beginDate != '' && this.$route.query.endDate != null && this.$route.query.beginendDateDate != '') {
        this.updateDateRange = [this.$route.query.beginDate, this.$route.query.endDate];
      }
      this.queryForm.creativeId = this.$route.query.creativeId;
    }
  },
  methods: {
    thousandSeparator(num) {
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0) ? '-' : '';
      let intPart = (div == -1) ? s : s.substring(0, div);
      let dotPart = (div == -1) ? '' : s.substring(div);
      let finalIntPart = '';
      while (intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0, intPart.length - 3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
    summaryMethod({columns, data}) {
      const ign = ["creativeUrl", "shortId", "performanceName", "localFilename", "offerName", "designer", "platform", "country"]
      const sums = [];
      let allExpendSum = 0;
      let impressionsSum = 0;
      let clicksSum = 0;
      let ctrSum = 0;
      let installSum = 0;
      let cvrSum = 0;
      let installCostSum = 0;
      if (data.length > 0) {
        data.forEach((row) => {
          allExpendSum += parseFloat(row.allExpend)
          impressionsSum += parseFloat(row.impressions)
          clicksSum += parseFloat(row.clicks)
          ctrSum += parseFloat(row.ctr)
          installSum += parseFloat(row.install)
          cvrSum += parseFloat(row.cvr)
          installCostSum += parseFloat(row.installCost)
        })
      }
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if ([0].includes(index)) {
            sums[index] = '合计'
          } else if (column.label && column.label === "花费") {
            sums[index] = this.thousandSeparator(allExpendSum.toFixed(2))
          } else if (column.label && column.label === "曝光") {
            sums[index] = impressionsSum = this.thousandSeparator(impressionsSum.toFixed(2))
          } else if (column.label && column.label === "点击") {
            sums[index] = clicksSum = this.thousandSeparator(clicksSum.toFixed(2))
          } else if (column.label && column.label === "CTR") {
            sums[index] = ctrSum = this.thousandSeparator(ctrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装") {
            sums[index] = installSum = this.thousandSeparator(installSum.toFixed(2))
          } else if (column.label && column.label === "CVR") {
            sums[index] = cvrSum = this.thousandSeparator(cvrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装成本") {
            sums[index] = installCostSum = this.thousandSeparator(installCostSum.toFixed(2))
          } else {
            // marco
            // sums[index] = this.tableColumnValue.map(item => Number(item[column.property]));
            sums[index] = ''
          }
        });
      }
      return sums;
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.performTime.blur();
      if (!isShowSelectOptions) this.$refs.performCreateUser.blur();
      if (!isShowSelectOptions) this.$refs.performPlatform.blur();
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    /**
     * 图片排序
     * @param val
     */
    sortImageChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.imgSortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.imgSortList = [];
      }
      this.onLoad(this.page);
    },
    /**
     * 视频排序
     * @param val
     */
    sortVideoChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.videoSortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.videoSortList = [];
      }
      this.onLoad(this.page);
    },
    loadOfferInfo(offerId, success) {
      if (offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res) => {
          success(res.data.data);
        }).catch(() => {
          success(null);
        });
      }
    },
    getAgencyTenantList() {
      getOutList(
        1,
        100,
        {offerId: this.offer},
      ).then(res => {
        this.agencyTenantList = res.data.data.records
      })
    },
    handleTabsClick(tab) {
      if (this.activeName != this.tabName) {
        this.page.currentPage = 1;
        this.tabName = this.activeName;
      }
    },
    refresh() {
      //refresh开始，这样写避免代码迁移太多
      /**
       * 调用设计师的字典
       * @type {string}
       */
      this.query.creativeId = null;
      this.query.offerId = this.offer;
      getDesignerList(this.offer).then((res) => {
        this.designerList = res.data.data;
      });
      getSysDictList("platforms,nation").then((map) => {
        this.platformList = map['platforms'];
        this.nationList = map['nation'];
      });
      getSubmitter(this.offer).then((res) => {
        this.submitterList = res.data.data;
      });
    },
    /**
     * 用来转换设计师id （方法）
     */
    designerChange(row) {
      let designers = row.designer.split(",");
      let designerList = this.designerList;
      let name = [];
      for (let i in designerList) {
        let designerId = designerList[i].id;
        let designerName = designerList[i].realName;
        for (let j in designers) {
          let designer = designers[j];
          if (designer === designerId) {
            name.push(designerName);
          }
        }
      }
      return name.join(",");
    },
    /**
     * 统计当前素材跑了多少个广告
     * @param row
     * @returns {string}
     */
    countAds(row) {
      let adsArr = row.ads.split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.page.currentPage = 1;
          this.onLoad(this.page);
        }
      });
    },
    resetSearch() {
      this.queryForm = {
        shortId: '',
        name: '',
        localFilename: '',
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        designer: null,
        creativeId: null,
        os: ''
      };
      this.updateDateRange = [];
      this.submitForm();
    },
    exportExcel() {
      const type = this.activeName;
      let sortList = (this.activeName == 0) ? this.imgSortList : this.videoSortList;
      let params = {}
      this.$confirm("是否导出数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        exportExcel(
          this.page.currentPage,
          this.page.pageSize,
          Object.assign({}, params, {offerId: this.offer}, this.query, {sortList: JSON.stringify(sortList)}, {eventData: this.selectedEventData}),
          type
        ).then(res => {
          let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          let url = window.URL.createObjectURL(new Blob([res.data]))
          let link = document.createElement("a")
          link.style.display = "none"
          link.href = url
          link.download = filename
          document.body.appendChild(link)
          link.click()
        })
      })
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },
    checkRow(row) {
      this.$refs.creativePerformanceDetail.showDialog({
        creativeId: row.creativeId,
        shortId: row.shortId,
        performanceName: row.performanceName,
        eventData: this.eventData,
        selectedEventData: this.selectedEventData,
        tableColumnValue: this.tableColumnValue
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.resetSearch();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      const type = this.activeName;
      let sortList = (this.activeName == 0) ? this.imgSortList : this.videoSortList;
      // marco
      const res = await getList(
        this.page.currentPage,
        this.page.pageSize,
        Object.assign({}, params, {offerId: this.offer}, this.buildSearch, {sortList: JSON.stringify(sortList)}, {eventData: this.selectedEventData}, {tempId: this.templateSelectOld}),
        type
      )
      let data = res.data.data;
      this.page.total = data.total;
      this.resultList = res.data.data.records;
      for (let i = 0; i < this.resultList.length; i++) {
        if (this.resultList[i].country != null && this.resultList[i].country != '') {
          let countryList = this.resultList[i].country.split(',');
          let set = new Set();
          countryList.forEach(c => {
            if (c != '') {
              set.add(c);
            }
          });
          this.resultList[i].country = Array.from(set).join(',');
        }
      }
      if (type === "0") {
        this.imageData = this.resultList;
      } else {
        this.videoData = this.resultList;
      }
      // console.log('imageData',this.imageData)
      // console.log('videoData',this.videoData)
      this.loading = false;
      // this.selectionClear();
    },
    onCreativeTagsClick(row) {
      let self = this;

      self.$nextTick(() => {
        self.creativeInfoDialog.name = row.performanceName;
        self.creativeInfoDialog.creativeId = row.id;
        self.creativeInfoDialog.dialogVisible = true;
      });
    },
    // marco
    handleSizeChange(val) {
      this.page.pageSize = val
      this.onLoad(this.page)
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.onLoad(this.page)
    },
    // 排序
    sortTableData(val) {
      if (this.activeName === '0') {
        this.sortImageChange(val)
      } else {
        this.sortVideoChange(val)
      }
    },
    // 获取模板
    async getTemplateList() {
      const {data: res} = await getTemplateList(this.offer, 1)
      this.templateList = res.data
    },
    handleModelClose() {
      this.saveDialog = false
      this.getTemplateList()
    },
    handleModelOpen() {
      this.saveDialog = true
      // 设置默认模板名
      this.templateDefaultName = this.userInfo.nick_name + '-' + Moment(new Date()).format('YYYYMMDDHHmmss') + '自定义模板'
      if (this.templateSelect && !isNaN(this.templateSelect)) {
        this.modelForm.modelFormat = '1'
        this.setTemplateName(false)
      } else {
        this.modelForm.modelFormat = '0'
        this.setTemplateName(true)
      }
    },
    findTemplateByName(name) {
      for (let i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].name === name) {
          return this.templateList[i].id
        }
      }
      return false
    },
    saveTemplate(data) {
      saveTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.saveTemplateloading = false
        this.handleModelClose()
      })
    },
    updateTemplate(data) {
      saveTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.saveTemplateloading = false
        this.handleModelClose()
      })
    },
    // 更换模板
    templateChange(val) {
      this.templateList.map(item => {
        if (item.id === val) {
          this.modelForm.modelFormat = '0'
          this.modelForm.modelName = this.templateDefaultName
          this.templateSelectOld = item.id
          const basicData = item.basicData.split(',')
          this.tableColumnValue = [...basicData]
          // updateUseTime(item.id)
        }
      })
      this.onLoad(this.page)
    },
    setTemplateName(flag) {
      if (flag) {
        this.modelForm.modelName = this.templateDefaultName
      } else {
        this.templateList.map(item => {
          if (item.id === this.templateSelectOld) {
            this.modelForm.modelName = item.name
          }
        })
      }
    },
    deleteTemplate(id, name) {
      this.$confirm("确定删除模板【" + name + "】?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteTemplate(id).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          })
          this.getTemplateList()
          this.templateSelect = null
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    /**
     * 保存模板
     */
    saveModel() {
      this.saveTemplateloading = true
      this.$refs.modelFormRef.validate(valid => {
        if (valid) {
          let data = {
            'id': this.templateSelectOld,
            'name': this.modelForm.modelName,
            'basicData': this.tableColumnValue.join(","),
            'eventData': '',
            'offerId': this.offer,
            'type': 1
          }
          if (this.modelForm.modelFormat === '0') {
            let id = this.findTemplateByName(data.name)
            if (id) {
              this.$confirm('此模板名已经存在，是否要覆盖该模板？', '提示', {
                confirmButtonText: '覆盖',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                data.id = id
                this.saveTemplate(data)
              })
            } else {
              delete data.id
              this.saveTemplate(data)
            }
          } else if (this.modelForm.modelFormat === '1' && data.id) {
            this.saveTemplate(data)
          } else {
            this.$message({
              type: "error",
              message: "当前未选择覆盖模板！"
            })
          }
        } else {
          this.saveTemplateloading = false
        }
      })
    },
    //获取表格表头显隐事件列表
    async getEventCreativeGroup() {
      const {data: res} = await getEventCreativeGroup(this.offer)

      this.tableColumnData = [...this.defaultTableColumnData, ...res.data.eventData]
      this.eventData = res.data.eventData
    },
    // 获取表格数据
    handleCloseTableColSet() {
      this.onLoad(this.page)
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    // 过滤侧边栏不同平添不可选择
    filterTableColumnData(val) {
      const plateforms = ['bigo','facebook','kwai','tiktok']
      this.tableColumnValue.forEach(item => {
        if (item.split('_')[0] === 'bigo') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'facebook') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'kwai') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'tiktok') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai') {
              item.disabled = true
            }
          })
        } else {
          if (!this.tableColumnValue.some(item => plateforms.includes(item.split('_')[0]))) {
            this.tableColumnData.forEach(item => {
              item.disabled = false
            })
          }
        }
      })
    },
    // 左边穿梭栏事件
    filterLeftTableColumnData(val) {
      console.log(222)
      const plateforms = ['bigo','facebook','kwai','tiktok']
      val.forEach(item => {
        if (item.split('_')[0] === 'bigo') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'facebook') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'kwai') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'tiktok') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai') {
              item.disabled = true
            }
          })
        }
      })
      if (!val.some(item => plateforms.includes(item.split('_')[0]))&&!this.tableColumnValue.some(item => plateforms.includes(item.split('_')[0]))){
        this.tableColumnData.forEach(item => {
          item.disabled = false
        })
      }
    },
    // 操作系统显示
    codeOS(val) {
      const arr = val ? val.split(',') : []
      let str = ''
      arr.forEach((item, index) => {
        switch (item) {
          case '1':
            str += 'Android'
            break
          case '2':
            str += 'IOS'
            break
          case '3':
            str += 'Website'
            break
          default:
            return
        }
        str += index < arr.length - 1 ? ',' : ''
      })
      return str
    }
  }
};
</script>

<style scoped lang="scss">
.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}

.search-form {

  /deep/ .el-form-item {
    margin-bottom: 0;
  }

}

/deep/ .el-table__body-wrapper {
  z-index: 2
}

/deep/ .search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 6px;
}

.el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after ::v-deep {
  position: absolute;
  right: 3px;
  font-family: element-icons;
  content: "\e6da";
  font-size: 12px;
  font-weight: 700;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.tab-header {
  font-size: 14px;
  margin-bottom: 15px;

  .tab-header-left {
    float: left;

    & > * {
      margin-right: 15px;
    }
  }

  .tab-header-right {
    float: right;
  }
}

.bottom-page {
  margin-top: 15px;

  .el-pagination {
    float: right;
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__header {
      .el-checkbox {
        .el-checkbox__input {
          display: none;
        }
      }
    }

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
        padding-bottom: 100px;
      }
    }
  }
}
.el-select {
  width: 100%;
}
</style>
